﻿using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;

using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

public partial class Probe_Users_ws_UsersList : System.Web.UI.Page
{

    #region Members
    string ConnStr = GetAppSetting("BIConnect");
    string strYear, strMonth;
    #endregion

    #region Common

    static public string GetAppSetting(String mName)
    {
        String vStr = null;
        string strPath =
    @"C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config";
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(strPath);
        XmlNode node = xmlDoc.SelectSingleNode(@"/configuration/appSettings");
        foreach (XmlNode keynode in node.ChildNodes)
        {
            string keyStr = keynode.Attributes["key"].Value;
            if (keyStr == mName)
            {
                vStr = keynode.Attributes["value"].Value;
                break;
            }
        }

        if (String.IsNullOrEmpty(vStr))
            vStr = "";

        return vStr;
    }

    #endregion

    #region Page Events

    protected override void OnPreInit(EventArgs e)
    {
        // Enabled trace in code
        this.Context.Trace.IsEnabled = false;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Params["Year"] != null)
            strYear = Request.Params["Year"].ToString();
        else
            strYear = DateTime.Now.Year.ToString();

        if (Request.Params["Month"] != null)
            strMonth = Request.Params["Month"].ToString();
        else
            strMonth = DateTime.Now.Month.ToString();

        XmlDocument xReturn = getXML();
        Response.ContentType = "text/xml";
        Response.Write(xReturn.OuterXml);
    }

    #endregion

    #region Data

    public XmlDocument getXML()
    {
        int Year = Convert.ToInt32(strYear);
        int Month = Convert.ToInt32(strMonth);

        XmlDocument xReturn = new XmlDocument();
        DataTable tbl = new DataTable("tbl");

        Exception err = new UsersHelper().GetUsers(ref tbl, @"http://localhost/");

        #region Make Table

        if (err != null)
        {
            tbl = new DataTable();

            tbl.Columns.Add("ID", typeof(string));
            tbl.Columns[0].Caption = "ID";
            tbl.Columns.Add("Name", typeof(string));
            tbl.Columns[1].Caption = "Name";

            DataRow r = tbl.NewRow();
            r[0] = "-1000";
            r[1] = "Ошибка получения данных.";
            tbl.Rows.Add(r);
        }

        #endregion

        #region XML stream

        using (StringWriter stringWriter = new StringWriter())
        {
            using (XmlTextWriter xmlTextwriter = new XmlTextWriter(stringWriter))
            {
                tbl.WriteXml(xmlTextwriter, XmlWriteMode.WriteSchema);
                xReturn.LoadXml(stringWriter.ToString());
                XmlNode xErrors = xReturn.CreateElement("Errors");
                if (err != null)
                {
                    XmlNode xErr = xReturn.CreateElement("Err");
                    xErr.InnerText = err.Message;
                    xErrors.AppendChild(xErr);
                }
                xReturn.ChildNodes[0].AppendChild(xErrors);
            }
        }

        #endregion

        return xReturn;
    }

    #endregion

    class UsersHelper
    {

        public Exception GetUsers(ref DataTable tbl, string sURL)
        {
            Exception ret = null;

            ret = MakeTableForUsersList(ref tbl);

            if (ret != null)
                return ret;

            try
            {
                using (SPSite site = new SPSite(sURL))
                {
                    using (SPWeb spUWeb = site.OpenWeb())
                    {

                        string OriginalUrl = site.Url;
                        SPServiceContext context = SPServiceContext.GetContext(site);
                        UserProfileManager uprofileManager = new UserProfileManager(context);

                        #region foreach

                        foreach (UserProfile uPr in uprofileManager)
                        {

                            DataRow r = tbl.NewRow();

                            if (uPr["UserProfile_GUID"].Value != null)
                                r["ID"] = uPr["UserProfile_GUID"].Value.ToString();
                            if (uPr["ID1C"].Value != null)
                                r["ID1C"] = uPr["ID1C"].Value.ToString();
                            if (uPr["ADGuid"].Value != null)
                                r["ADGuid"] = uPr["ADGuid"].Value.ToString();
                            if (uPr["PreferredName"].Value != null)
                                r["FullName"] = uPr["PreferredName"].Value.ToString();
                            if (uPr["FirstName"].Value != null)
                                r["FirstName"] = uPr["FirstName"].Value.ToString();
                            if (uPr["LastName"].Value != null)
                                r["LastName"] = uPr["LastName"].Value.ToString();
                            if (uPr["SPS-JobTitle"].Value != null)
                                r["Staff"] = uPr["SPS-JobTitle"].Value.ToString();
                            if (uPr["Department"].Value != null)
                                r["Department"] = uPr["Department"].Value.ToString();
                            if (uPr["Office"].Value != null)
                                r["Office"] = uPr["Office"].Value.ToString();
                            if (uPr["WorkPhone"].Value != null)
                                r["WorkPhone"] = uPr["WorkPhone"].Value.ToString();
                            if (uPr["PictureUrl"].Value != null)
                                r["ImageUrl"] = uPr["PictureUrl"].Value.ToString();
                            else
                                r["ImageUrl"] = sURL + "/_layouts/IMAGES/no-photo.png";
                            if (uPr.PersonalSite != null)
                                r["SiteUrl"] = uPr.PersonalSite.Url.ToString();

                            DateTime dtBirthday, dtHireDate;
                            if (uPr["SPS-Birthday"].Value != null)
                            {
                                dtBirthday = DateTime.Parse(uPr["SPS-Birthday"].Value.ToString());
                                r["Birthday"] = dtBirthday;
                            }
                            if (uPr["SPS-HireDate"].Value != null)
                            {
                                dtHireDate = DateTime.Parse(uPr["SPS-HireDate"].Value.ToString());
                                r["HireDate"] = dtHireDate;
                            }

                            tbl.Rows.Add(r);
                        }

                        #endregion

                    }
                }
            }
            catch(Exception err)
            {
                ret = new Exception(err.Message, err);
            }                
            
            return ret;
        }

        Exception MakeTableForUsersList(ref DataTable tbl)
        {
            Exception ret = null;
            tbl = new DataTable("Users");
            tbl.Columns.Add("ID", typeof(Guid));
            tbl.Columns.Add("ID1C", typeof(string));
            tbl.Columns.Add("ADGuid", typeof(string));
            tbl.Columns.Add("FirstName", typeof(string));
            tbl.Columns.Add("LastName", typeof(string));
            tbl.Columns.Add("FullName", typeof(string));
            tbl.Columns.Add("Department", typeof(string));
            tbl.Columns.Add("Office", typeof(string));
            tbl.Columns.Add("ImageUrl", typeof(string));
            tbl.Columns.Add("SiteUrl", typeof(string));
            tbl.Columns.Add("WorkPhone", typeof(string));
            tbl.Columns.Add("Mail", typeof(string));
            tbl.Columns.Add("Staff", typeof(string));
            tbl.Columns.Add("Birthday", typeof(DateTime));
            tbl.Columns.Add("HireDate", typeof(DateTime));
         
            return ret;
        }

    }

    class dsData
    {
        private int _id;
        public int ID { get { return _id; } set { _id = value; } }
        private string _FirstName = "";
        public string FirstName { get { return _FirstName; } set { _FirstName = value; } }
        private string _LastName = "";
        public string LastName { get { return _LastName; } set { _LastName = value; } }
        private string _Department = "";
        public string Department { get { return _Department; } set { _Department = value; } }
        private string _Office = "";
        public string Office { get { return _Office; } set { _Office = value; } }
        private string _ImageUrl = "";
        public string ImageUrl { get { return _ImageUrl; } set { _ImageUrl = value; } }
        private string _SiteUrl = "";
        public string SiteUrl { get { return _SiteUrl; } set { _SiteUrl = value; } }
        private string _Phone = "";
        public string Phone { get { return _Phone; } set { _Phone = value; } }
        private string _Mail = "";
        public string Mail { get { return _Mail; } set { _Mail = value; } }
        private string _Staff = "";
        public string Staff { get { return _Staff; } set { _Staff = value; } }
        private DateTime _Birthday;
        public DateTime Birthday { get { return _Birthday; } set { _Birthday = value; } }
        private DateTime _HireDate;
        public DateTime HireDate { get { return _HireDate; } set { _HireDate = value; } }
        private string _FullName = "";
        public string FullName { get { return _FullName; } set { _FullName = value; } }
    }


}